package com.js.rtu.fragment.forth;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.AlarmTypeConfig;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.fragment.third.DebugViewPagerFragment;
import com.js.rtu.mvp.bean.Cmd40Bean;
import com.js.rtu.mvp.bean.base.CommonBean;
import com.js.rtu.mvp.present.Cmd40Presenter;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;

import org.angmarch.views.NiceSpinner;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 报警历史查询
 * 第1字节为查询报警类型及条件，类型说明见表九；
 * 第2-7字节为查询起始时间（年、月、日、时、分、秒共 6 字节）；
 * 第8-13字节为查询结束时间，（年、月、日、时、分、秒共 6 字节）；
 * 当第1字节设定查询条件与时间无关时，仍需要填充起始时间和结束时间（共12字节）；
 * EE EE 31 32 33 34 35 36 37 38 XX 00 40 + 1D + 16 05 05 10 19 1B + 16 05 05 10 1C 1B + XX XX FF FF
 */
public class AlarmFragment extends BaseFragment {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.tv_start)
    EditText tvStart;
    @BindView(R.id.tv_end)
    EditText tvEnd;
    @BindView(R.id.sp_type)
    NiceSpinner spType;
    @BindView(R.id.sp_mode)
    NiceSpinner spMode;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    String type = AlarmTypeConfig.STR_0000;
    String mode = AlarmTypeConfig.STR_MODEL_0001;
    String start = "";
    String end = "";

    @BindView(R.id.tv_total)
    EditText tvTotal;
    @BindView(R.id.tv_next)
    EditText tvNext;
    boolean hasMore;
    public static AlarmFragment newInstance() {
        Bundle args = new Bundle();
        AlarmFragment fragment = new AlarmFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_forth_alarm;
    }

    @Override
    protected void initView() {
        tvStart.setText(new SimpleDateFormat("yyyy/MM/dd 00:00:00", Locale.CHINA).format(new Date()));
        tvEnd.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA).format(new Date()));
        start = tvStart.getText().toString();
        end = tvEnd.getText().toString();
        loadRootFragment(R.id.fl_container, DebugViewPagerFragment.newInstance());//22_07设置终端工作参数
        initToolbarNav(toolbar);
        toolbarTitle.setText("报警历史查询");
        spType.attachDataSource(AlarmTypeConfig.getTypeList());
        spType.setOnSpinnerItemSelectedListener((parent, view, position, id) -> type = (String) parent.getItemAtPosition(position));
        spType.setSelectedIndex(0);

        spMode.attachDataSource(AlarmTypeConfig.getModelList());
        spMode.setOnSpinnerItemSelectedListener((parent, view, position, id) -> {
            mode = (String) parent.getItemAtPosition(position);
            //当第1字节设定查询条件与时间无关时，仍需要填充起始时间和结束时间
            llTime.setVisibility(mode.equals(AlarmTypeConfig.STR_MODEL_0000) ? View.GONE : View.VISIBLE);
        });
        spMode.setSelectedIndex(1);

        llTime.setVisibility(mode.equals(AlarmTypeConfig.STR_MODEL_0000) ? View.GONE : View.VISIBLE);
    }


    @OnClick({R.id.tv_start, R.id.tv_end, R.id.btn_set, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start:
                showDialog(tvStart);
                break;
            case R.id.tv_end:
                showDialog(tvEnd);
                break;
            case R.id.btn_set:

//
//                Cmd40Presenter presenter = new Cmd40Presenter();
//                CommonBean<Cmd40Bean> bean = presenter.paseData(msg);
//                presenter.setInfo(bean);
                start = tvStart.getText().toString();
                end = tvEnd.getText().toString();
                if (start.isEmpty() || end.isEmpty()) {
                    toastShow("请选择时间");
                    return;
                }

                tvTotal.setText("");
                tvNext.setText("");
                sendData40(start, end);
                break;
            case R.id.btn_next:
                String msg = tvTotal.getText().toString();
                if (msg.contains("/")) {
                    String[] num = msg.split("/");
                    Log.e("xxxxx",num.length+"");
                    if (num.length != 2) {
                        return;
                    }
                    if (num[0].equals(num[1])) {
                        toastShow("该查询条件无更多报警");
                        return;
                    }
                } else {
                    toastShow("请先查询");
                    return;
                }

                String next = tvNext.getText().toString();
                end = tvEnd.getText().toString();
                if (start.isEmpty() || end.isEmpty()) {
                    toastShow("请选择时间");
                    return;
                }
                sendData40(next, end);
                break;
        }
    }


    /**
     * 报警历史查询
     */
    private void sendData40(String start, String end) {
        start = Z2String(start, "yyyy/MM/dd HH:mm:ss", "yy MM dd HH mm ss");
        end = Z2String(end, "yyyy/MM/dd HH:mm:ss", "yy MM dd HH mm ss");
        StringBuilder stringBuilder = new StringBuilder();
        String str_model;
        str_model = AlarmTypeConfig.getHHHH(mode) + AlarmTypeConfig.getType(type);
//        if (mode.equals("无查询条件")) {
//            str_model = "0000" + AlarmTypeConfig.getType(type);
//        } else if (mode.equals("根据起止时间查询")) {
//            str_model = "0001" + AlarmTypeConfig.getType(type);
//        } else if (mode.equals("查询连接错误记录")) {
//            str_model = "0010" +AlarmTypeConfig.getType(type);
//        } else if (mode.equals("查询连接记录且需要根据起止时间查询")) {
//            str_model = "0011" + AlarmTypeConfig.getType(type);
//        } else {
//            str_model = "0000" +AlarmTypeConfig.getType(type);
//        }
        Log.e("xxxxx",start);
        Log.e("xxxxx",end);
        int ten = Integer.parseInt(str_model, 2);//2--》10
        str_model = Integer.toHexString(ten);//10--》16
        if (str_model.length() != 2) {
            str_model = "0" + str_model;
        }
        stringBuilder.append(str_model).append(" ");
        String[] str_start = start.split(" ");
        for (String s : str_start) {
            stringBuilder.append(String.format("%02x", Integer.parseInt(s))).append(" ");
        }
        String[] str_end = end.split(" ");
        for (String s : str_end) {
            stringBuilder.append(String.format("%02x", Integer.parseInt(s))).append(" ");
        }
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_40, stringBuilder.substring(0, stringBuilder.length() - 1));


        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                String[] data = msg.split(" ");
                if (data.length >= 12 && data[12].equals("40")) {
                    Cmd40Presenter presenter = new Cmd40Presenter();
                    CommonBean<Cmd40Bean> bean = presenter.paseData(msg);
                    presenter.setInfo(bean);
                    String total = "";
                     hasMore = false;
                    if (bean.getData().getCur() != null) {
                        total = bean.getData().getCur() + "/";
                    }
                    if (bean.getData().getTotal() != null) {
                        total = total + bean.getData().getTotal();
                    }
                    if (bean.getData().getCur() != null&&bean.getData().getTotal() != null){
                        if (Integer.parseInt(bean.getData().getCur())== Integer.parseInt(bean.getData().getTotal())) {
                            hasMore=true;
                        }
                    }
                    tvTotal.setText(total);
                    List<Cmd40Bean.AlarlBean> list = bean.getData().getAlarlBeans();
                    if (list != null) {
                        Cmd40Bean.AlarlBean alarlBean = list.get(list.size() - 1);
                        if (alarlBean.getAlarmTime() != null) {
                            tvNext.setText(alarlBean.getAlarmTime());
                        }
                    }


                }

            }

            @Override
            public void onFail(String err) {
                BasePopupView popupView = new XPopup.Builder(_mActivity)
                        .asConfirm("无数据", err,
                                "", "确定",
                                null, null, true);
                popupView.show();

//                toastShow("无数据" + err);
            }
        });

    }


    /**
     * 时间选择
     */
    private void showDialog(TextView textView) {
        TimePickerView pvTime = new TimePickerBuilder(_mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                textView.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA).format(date));


            }
        }).setType(new boolean[]{true, true, true, true, true, true})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(16)//标题文字大小
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.show();
    }

    /**
     * 带时区时间转String
     *
     * @return
     */
    public static String Z2String(String time, String from, String to) {
//        String MSG="2021-07-22T14:28:41.257+08:00";
        SimpleDateFormat sdf = new SimpleDateFormat(from, Locale.CHINA);
        Date applyDate = null;
        try {
            applyDate = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        SimpleDateFormat sdf1 = new SimpleDateFormat(to, Locale.CHINA);
        String stringDate = "";
        if (applyDate != null) {
            stringDate = sdf1.format(applyDate);
        }
        return stringDate;
    }
}
